class Solution(object):
    def minOperations(self, grid, x):
        m = len(grid)
        n = len(grid[0])
        ans = [0] * m * n
        for i in range(m):
            for j in range(n):
                ans[i * n + j] = grid[i][j]
        ans.sort()
        min_val = ans[0]
        if all([(num - min_val) % x == 0 for num in ans]):
            mid_val = ans[len(ans) // 2]
            return sum([abs(num - mid_val) // x for num in ans])
        else:
            return -1